from flask import Blueprint, render_template, g, flash
from flask_login import current_user
from appli import app,ObjectToStr,PrintInCharte,database,gvg,gvp,XSSEscape,FormatError
from pathlib import Path
from flask_security import Security, SQLAlchemyUserDatastore
from flask_security import login_required
from flask_security.decorators import roles_accepted
from appli.search.leftfilters import getcommonfilters
import os,time,math,collections,appli
from appli.database import GetAll,GetClassifQualClass,ExecSQL,db,GetAssoc2Col
import appli.project.main

######################################################################################################################
@app.route('/prj/merge/<int:PrjId>', methods=['GET', 'POST'])
@login_required
def PrjMerge(PrjId):
    Prj=database.Projects.query.filter_by(projid=PrjId).first()
    if Prj is None:
        flash("Project doesn't exists",'error')
        return PrintInCharte("<a href=/prj/>Select another project</a>")
    if not Prj.CheckRight(2): # Level 0 = Read, 1 = Annotate, 2 = Admin
        flash('You cannot edit settings for this project','error')
        return PrintInCharte("<a href=/prj/>Select another project</a>")
    g.headcenter="<h4><a href='/prj/{0}'>{1}</a></h4>".format(Prj.projid,XSSEscape(Prj.title))
    txt = "<h3>项目合并/融合 </h3>"

    if not gvg('src'):
        txt += """<ul><li>你可以合并你能够管理的项目
<li>两个项目的用户权限将被添加
<li>该工具能够将两个项目合并到一个项目中（命名为当前项目），添加的项目将被自动删除。如果两个项目之间的对象数据不一致，则：
<ul><li>新的数据字段被添加到当前项目中
    <li>最终项目将包含部分文档化的数据字段。
</ul><li> 注意：下一个界面将指出兼容性问题（如果存在），并让您确认合并操作。
</ul>
                """
        sql="select p.projid,title,status,coalesce(objcount,0) objcount,coalesce(pctvalidated,0) pctvalidated,coalesce(pctclassified,0) pctclassified from projects p"
        if not current_user.has_role(database.AdministratorLabel):
            sql+=" Join projectspriv pp on p.projid = pp.projid and pp.member=%d"%(current_user.id,)
        sql+=" where p.projid!=%d order by title"%Prj.projid
        res = GetAll(sql,doXSSEscape=True) #,debug=True
        txt+="""<table class='table table-bordered table-hover table-verycondensed'>
                <tr><th></td><th width=120>ID</td><th>标题</td><th width=100>状态</th><th width=100>对象数量</th>
            <th width=100>% 验证百分比</th><th width=100>% 分类百分比</th></tr>"""
        for r in res:
            txt+="""<tr><td><a class="btn btn-primary" href='/prj/merge/{activeproject}?src={projid}'>选择</a></td>
            <td> {projid}</td>
            <td>{title}</td>
            <td>{status}</td>
            <td>{objcount:0.0f}</td>
            <td>{pctvalidated:0.2f}</td>
            <td>{pctclassified:0.2f}</td>
            </tr>""".format(activeproject=Prj.projid,**r)
        txt+="</table>"
        return PrintInCharte(txt)

    PrjSrc=database.Projects.query.filter_by(projid=int(gvg('src'))).first()
    if PrjSrc is None:
        flash("Source project doesn't exists",'error')
        return PrintInCharte("<a href=/prj/>Select another project</a>")
    if not PrjSrc.CheckRight(2): # Level 0 = Read, 1 = Annotate, 2 = Admin
        flash('You cannot merge for this project','error')
        return PrintInCharte("<a href=/prj/>Select another project</a>")
    txt += """<h4>项目 : {0} - {1} (这个项目将被销毁)</h4>
            """.format(PrjSrc.projid,XSSEscape(PrjSrc.title))
    if not gvg('merge'): # Ici la src à été choisie et vérifiée
        if PrjSrc.mappingobj!=Prj.mappingobj:
            flash("Object mapping differ With source project ","warning")
        if PrjSrc.mappingsample!=Prj.mappingsample:
            flash("Sample mapping differ With source project ","warning")
        if PrjSrc.mappingacq!=Prj.mappingacq:
            flash("Acquisition mapping differ With source project ","warning")
        if PrjSrc.mappingprocess!=Prj.mappingprocess:
            flash("Process mapping differ With source project ","warning")
        txt += FormatError(""" <span class='glyphicon glyphicon-warning-sign'></span>
        警告 项目 {1} - {2}<br>
        将被销毁，其内容将转移至目标项目中，<br>
        这个操作不可逆。</p>
        <br><a class='btn btn-lg btn-warning' href='/prj/merge/{0}?src={1}&merge=Y'>开始合并项目</a>        
        """,Prj.projid,PrjSrc.projid,XSSEscape(PrjSrc.title),DoNotEscape=True)
        return PrintInCharte(txt)

    if gvg('merge')=='Y':
        ExecSQL("update acquisitions set projid={0} where projid={1}".format(Prj.projid,PrjSrc.projid))
        ExecSQL("update process set projid={0} where projid={1}".format(Prj.projid,PrjSrc.projid))
        ExecSQL("update samples set projid={0} where projid={1}".format(Prj.projid,PrjSrc.projid))
        ExecSQL("update obj_head set projid={0} where projid={1}".format(Prj.projid,PrjSrc.projid))
        ExecSQL("update part_projects set projid={0} where projid={1}".format(Prj.projid,PrjSrc.projid))
        # garde le privilege le plus elevé des 2 projets
        ExecSQL("""UPDATE projectspriv ppdst
                  set privilege=case when 'Manage' in (ppsrc.privilege,ppdst.privilege) then 'Manage'
                        when 'Annotate' in (ppsrc.privilege,ppdst.privilege) then 'Annotate'
                        else 'View' end
                from projectspriv  ppsrc
                where ppsrc.projid={1} and ppdst.projid={0} and ppsrc.member=ppdst.member""".format(Prj.projid,PrjSrc.projid),debug=True)
        # Transfere les privilege depuis le projet source
        ExecSQL("""update projectspriv
                set projid={0}
                where projid={1} and member not in (select member from projectspriv where projid={0})""".format(Prj.projid,PrjSrc.projid))
        # Efface ceux qui etait des 2 cotés
        ExecSQL("delete from projectspriv where projid={0}".format(PrjSrc.projid))
        ExecSQL("delete from projects where projid={0}".format(PrjSrc.projid))
        appli.project.main.RecalcProjectTaxoStat(Prj.projid)
        appli.project.main.UpdateProjectStat(Prj.projid)

        txt+="<div class='alert alert-success' role='alert'>合并操作成功</div>"
        txt+="<br><a class='btn btn-lg btn-primary' href='/prj/%s'>返回目标项目</a>"%Prj.projid
        return PrintInCharte(txt)



